package com.example.myapplication.network;

import android.content.Context;
import com.example.myapplication.api.ApiService;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit网络客户端配置
 */
public class RetrofitClient {
    
    // 云平台基础URL
    private static final String BASE_URL = "http://192.168.30.240:8080/";
    
    private static RetrofitClient instance;
    private ApiService apiService;
    private Context context;

    private RetrofitClient(Context context) {
        this.context = context;
        // 创建HTTP日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 创建认证拦截器
        AuthInterceptor authInterceptor = new AuthInterceptor(context);

        // 创建OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(authInterceptor)  // 添加认证拦截器
                .addInterceptor(loggingInterceptor)
                .connectTimeout(10, TimeUnit.SECONDS)  // 10秒连接超时
                .readTimeout(10, TimeUnit.SECONDS)     // 10秒读取超时
                .writeTimeout(10, TimeUnit.SECONDS)    // 10秒写入超时
                .retryOnConnectionFailure(true)
                .build();
        
        // 创建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        // 创建API服务实例
        apiService = retrofit.create(ApiService.class);
    }
    
    /**
     * 获取RetrofitClient单例实例
     * @param context 应用上下文
     * @return RetrofitClient实例
     */
    public static synchronized RetrofitClient getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitClient(context);
        }
        return instance;
    }
    
    /**
     * 获取API服务实例
     * @return ApiService实例
     */
    public ApiService getApiService() {
        return apiService;
    }
}
